package com.wzw.shoppingcart.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzw.shoppingcart.entity.CartLine;
import com.wzw.shoppingcart.entity.Product;
import com.wzw.shoppingcart.mapper.CartLineMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


/**
 *@author wzw
 * 2023/4/8
 */
@Service
public class CartLineService extends ServiceImpl<CartLineMapper, CartLine> {


    public boolean exist(Integer productId, Integer userId) {
        return lambdaQuery()
                .eq(CartLine::getProductId, productId)
                .eq(CartLine::getUserId, userId)
                .exists();
    }

    public boolean addCount(Integer amount, Integer productId, Integer userId) {
        CartLine cartLine = getCartLine(productId, userId);

        return lambdaUpdate().eq(CartLine::getProductId, productId)
                .eq(CartLine::getUserId, userId)
                .set(CartLine::getProductCount, cartLine.getProductCount() + amount)
                .update();
    }


    public CartLine getCartLine(Integer productId, Integer userId) {
        return lambdaQuery()
                .eq(CartLine::getProductId, productId)
                .eq(CartLine::getUserId, userId)
                .one();
    }


    public List<Product> getProducts(List<CartLine> cartLines) {
        return cartLines.stream()
                .map(CartLine::getProduct)
                .collect(Collectors.toList());
    }

    public List<CartLine> getCartLines(Integer userId){
       return lambdaQuery()
               .eq(CartLine::getUserId,userId)
               .list();
    }
}
